//运营管理===>营销活动页面---代运营页面
import React, {Component} from 'react';
import $ from 'jquery';
import { message, Form, Row, Col, Input, Table, Modal, Select } from 'antd';
import Button from '../../../components/button/button'
import * as tools from '../../../tools/tools.js';
import SearchPanel from '../../../components/SearchPanel/SearchPanel';      //搜索
import ViewDetail from '../viewdetails/viewdetails'  //营销详情
import AddReplaceShop from '../AddReplaceShop/AddReplaceShop'   //代运营添加店铺
import OperationDetails from '../OperationDetails/OperationDetails'     //详情
import OperationAccount from '../OperationAccount/OperationAccount'

class MarketingActivities extends Component{
  constructor(props) {
    super(props);
    this.columnstype1 = [   //表格列的配置项--营销活动列表
        { title: '优惠券id', dataIndex: 'shop_coupons_id', key: 'shop_coupons_idtype1',fixed: 'left' ,className:'iddisplay',
        sorter: (a, b) => a.number - b.number },
        { title: '活动id',dataIndex:'activities_id',key:'activities_idtype1',className:'iddisplay'},
        { title: '创建时间', dataIndex: 'created_at', key: 'created_attype1'},
        { title: '店铺编号', dataIndex: 'shop_identifier', key: 'shop_identifiertype1',},
        { title: '店铺名称', dataIndex: 'shop_name', key: 'shop_nametype1'},
        { title: '店铺账号', dataIndex: 'bosses_mobile', key: 'bosses_mobiletype1' },
        { title: '区域', dataIndex: 'address', key: 'addresstype1' },
        { title: '行业', dataIndex: 'last_industrie_name', key: 'last_industrie_nametype1' },
        { title: '活动名称', dataIndex: 'activities_name', key: 'activities_nametype1' },
        { title: '投放渠道', dataIndex: 'channel', key: 'channeltype1' },
        { title: '优惠类型', dataIndex: 'coupon_type', key: 'coupon_typetype1' ,
        render:(text)=><span>{text == 0?"空":(text ==1?'新客券':(text ==2?"回头客券":"营销券"))}</span>},
        { title: '优惠内容', dataIndex: 'discount_type', key: 'discount_typetype1' },
        { title: '投放数量', dataIndex: 'quantitynum', key: 'quantitynumtype1' },
        { title: '核销数量', dataIndex: 'coupon_number', key: 'coupon_numbertype1'},
        { title: '核销金额', dataIndex: 'coupon_money', key: 'coupon_moneytype1' },
        { title: '订单金额', dataIndex: 'order_amount',key:'Order amounttype1'},
        { title: '营销状态', dataIndex: 'activity_type', key: 'activity_typetype1',
        render: (text) => <span>{text ==1?"进行":(text ==2?"暂停":"结束")}</span>},
        {title: '查看' , dataIndex:'chakan',key:'chakan',
        render:(text)=><span style={{color:'#4C8EDB',cursor:'pointer'}} onClick={this.lookover}>查看</span>}
    ]
    this.columnstype2 = [         //表格列的配置项--代运营店铺列表
        { title: 'sid',dataIndex:'sid',key:'sidtype2',fixed: 'left',className:'iddisplay'},
        { title: 'id',dataIndex:'id',key:'idtype2',fixed: 'left',className:'iddisplay'},
        { title: '店铺编号', dataIndex: 'shop_identifier', key: 'shop_identifiertype2',},
        { title: '店铺名称', dataIndex: 'shop_name', key: 'shop_nametype2'},
        { title: '店铺账号', dataIndex: 'shop_bosses_mobile', key: 'shop_bosses_mobiletype2' },
        { title: '投入', dataIndex: 'into', key: 'intotype2' },
        { title: '产出', dataIndex: 'output', key: 'outputtype2' },
        { title: 'ROI', dataIndex: 'discount', key: 'discounttype2' },
        { title: '状态', dataIndex: 'status', key: 'statustype2',
        render:(text)=><span>{text == 1?"待确认":(text ==2?"运行":(text ==3?"暂停":(text ==4?"待结算":(text ==5?"已结束":"打款结束"))))}</span> },
        { title: '打款', dataIndex: 'is_pay', key: 'is_paytype2',
        render:(text)=><span>{text ==1?"未打款":"已打款"}</span> },
        { title: '优惠活动', dataIndex: 'activitie_num', key: 'activitie_numtype2',
        render:(text)=><span>{text ==0?"否":"是"}</span> },
        { title: '订单金额', dataIndex: 'order_money', key: 'order_moneytype2' },
        { title: '不参与优惠金', dataIndex: 'order_undiscount', key: 'order_undiscounttype2' },
        { title: '参与优惠金', dataIndex: 'order_discount', key: 'order_discounttype2' },
        { title: '不优惠金占比', dataIndex: 'order_proportion', key: 'order_proportiontype2'},
        { title: '手续费补贴', dataIndex: 'subsidy', key: 'subsidytype2' },
        { title: '最新编辑时间', dataIndex: 'updated_at', key: 'updated_attype2',
        render:(text)=><span>{new Date(text * 1000).toLocaleDateString()}</span>},
        { title: '操作', dataIndex: 'caozuo', key: 'caozuotype2',
        render:(text)=><span style={{color:'#4C8EDB',cursor:'pointer'}} onClick={this.editmodify}>查看</span>}
    ]
    this.columns = this.props.location.state.id == 29?this.columnstype1:(this.props.location.state.id == 31?this.columnstype2:false)
    this.state = {
        detailvisible:false,
        newbutton:{    //按钮样式
            background: '#D8D8D8',
            borderRadius: '100px',
            width:'88px',
            height:'30px',
            color:'#999999',
            marginLeft:'30px',
          },
        searchtype1 : [   //搜索data--营销活动
            {
                id : 'identifier',
                name : '店铺编号',
                type : 1,
            },
            {
                id : 'shop_name',
                name : '店铺名',
                type : 1
            },
            {
                id : 'boss_mobile',
                name : '店铺账户',
                type : 1,//input select
            },
            {
                id : 'province_id',
                name : '省',
                type : 1,//input select
            },
            {
                id : 'city_id',
                name : '市',
                type : 1,//input select
            },
            {
                id : 'sindustry_id',
                name : '二级分类',
                type : 1,//input select
            },
            {
                id : 'activitie_name',
                name : '活动名称',
                type : 1,//input select
            },
            {
                id : 'channel',
                name : '投放渠道',
                type : 2,
                options :[
                    {//1否买单即享，2加入商圈联盟，3消费返券，4会员直派
                        val :1,
                        text:'买单既享'
                    },
                    {
                        val:2,
                        text:'加入商圈联盟'
                    },
                    {
                        val:3,
                        text:'消费返券'
                    },
                    {
                        val:2,
                        text:'会员直派'
                    }
                ]
            },
            {
                id : 'discount_type',
                name : '优惠券折扣类型',
                type : 2,
                options :[
                    {//1，满减 2，满折 3，满减并叠加
                        val :1,
                        text:'满减'
                    },
                    {
                        val:2,
                        text:'满折'
                    },
                    {
                        val:3,
                        text:'满减并叠加'
                    }
                ]
            },
            {
                id : 'activity_type',
                name : '营销状态',
                type : 2,
                options : [
                    {//1，进行 2，暂停 3，结束
                        val : 1,
                        text : '进行'
                    },{
                        val : 2,
                        text : '暂停'
                    },
                    {
                        val : 3,
                        text : '结束'
                    }
                ]
            }
        ],
        searchtype2:[       //代运营
            {
                id : 'shop_identifier',
                name : '店铺编号',
                type : 1,
            },
            {
                id : 'shop_name',
                name : '店铺名称',
                type : 1
            },
            {
                id : 'boss_mobile',
                name : '店铺账户',
                type : 1,//input select
            },
            {
                id : 'status',
                name : '状态',
                type : 2,
                options:[
                    {
                        val :1,
                        text:'待确认'
                    },
                    {
                        val:2,
                        text:'运行'
                    },
                    {
                        val:3,
                        text:'暂停'
                    },
                    {
                        val:4,
                        text:'待结算'
                    },
                    {
                        val:5,
                        text:'已结算'
                    },
                    {
                        val:6,
                        text:'打款结束'
                    }
                ]
            },
            {
                id : 'sindustry_id',
                name : '二级分类',
                type : 1,//input select
            },
            {
                id : 'operate_username',
                name : '代运营账户',
                type : 1,
            },
            {
                id : 'operate_name',
                name : '代运营姓名',
                type : 1,
            },
            {
                id : 'operate_mobile',
                name : '代运营电话',
                type : 1,
            },
            {
                id:'time',
                name:'开始时间',
                type:3
            }
        ],
        cTabContent:null,
        addReplacevisible:false,
        numtype:null,
        editmodifyvisible:false,
        Accountvisible:false,
        disabled:'disabled'
    }
}
componentWillMount(){
    tools.loginView(this).then(
    this.agentlist()
    )
}
agentlist=()=>{                //获取table列表内容

        $.ajax({
        url: tools.apiUrl+this.props.location.state.url,  //?page=1
        type :'Post',
        data:{
            'token':localStorage.token
        },
        success:(res)=>{
            let service = res.result.bank_service
            let data = res.result.data
            if(res.status ==1){
                let cTabContent = this.props.location.state.id ==29?this.tabDataFrom(data):(this.props.location.state.id ==31?this.replaceDataForm(data,service):false);
                this.setState({
                    marketpage:res.result.page,
                    cTabContent,
                })
            }else{
            message.error(res.msg)
            }
        }
        })
} 
tabDataFrom=(data)=>{       //重新定义table数据的格式--营销活动管理
    return data.map( val=>{
        let channel = (val.is_immediate ==0?'':'买单即享,')+(val.is_league ==0?'':'消费返券,')+(val.is_return ==0?'':'消费返券,')+(val.is_vip ==0?'':'会员直派');   //投放渠道
        let discount_type = val.discount_type ==1?"满"+val.discount_base/100+"减"+val.discount/100:   //优惠内容
            (val.discount_type ==2?"满"+val.discount_base/100+"折"+val.discount/10:"每满"+val.discount_base/100+"减"+val.discount/100)
        let quantitynum = val.limit_type ==1?"不限":val.quantity;         //投放数量
        let coupon_number = val.coupon_discount?val.coupon_discount.split('|')[1]:0   //核销数量
        let coupon_money = val.coupon_discount?(val.coupon_discount.split('|')[0])/100:0   //核销金额
        let order_amount = val.coupon_discount?(val.coupon_discount.split('|')[2])/100:0
        let address = val.province_name+'-'+val.city_name+'-'+val.area_name
        
        return {
            shop_coupons_id:val.shop_coupons_id,
            activities_id:val.activities_id,
            created_at:new Date(val.created_at * 1000).toLocaleDateString(),
            shop_identifier:val.shop_identifier,
            shop_name:val.shop_name,
            bosses_mobile:val.bosses_mobile,
            address,
            last_industrie_name:val.last_industrie_name,
            activities_name:val.activities_name,
            channel,
            coupon_type:val.coupon_type,
            discount_type,
            quantitynum,
            coupon_number,
            coupon_money,
            order_amount,
            activity_type:val.activity_type,
        }
    })
}
replaceDataForm=(data,service)=>{       //重新定义table数据---代运营
    return data.map( val=>{
        let order_money = val.order_count?val.order_count.split('|')[0]/100:0   //订单金额
        let order_undiscount = val.order_count?(val.order_count.split('|')[1])/100:0   //不参与优惠金
        let order_discount = val.order_count?(val.order_count.split('|')[2])/100:0      //参与优惠金
        let order_proportion = order_money?(order_undiscount/order_money).toFixed(2):"无"    //不优惠金占比
        let subsidy = order_undiscount*service                //手续费补贴
        return{
            id:val.id,
            sid:val.sid,
            shop_identifier:val.shop_identifier,
            shop_name:val.shop_name,
            shop_bosses_mobile:val.shop_bosses_mobile,
            into:val.into/100,
            output:val.output/100,
            discount:val.discount/100,
            status:val.status,
            is_pay:val.is_pay,
            activitie_num:val.activitie_num,
            temp_id:val.temp_id,
            operate_type:val.operate_type,
            order_money,
            order_undiscount,
            order_discount,
            order_proportion,
            subsidy,
            updated_at:val.updated_at,
            caozuo:val.caozuo,

        }
    })
}

lookover=(e)=>{  //查看详情回调
    let cid = e.target.parentNode.parentNode.firstChild.nextSibling.innerText  //优惠券id
    let aid = e.target.parentNode.parentNode.firstChild.nextSibling.nextSibling.innerText  //活动id
    tools.loginView(this).then(
        $.ajax({
            type:'post',
            url:tools.apiUrl+"operation/shop_activity_info"  ,
            data:{
                token:localStorage.token,
                cid,								//优惠券id  
                aid,
            },
            success:(res)=>{
                if(res.status ==1){
                    this.setState({
                        viewdata:res.result,
                        detailvisible:true
                    })
                }else{
                    message.error(res.msg)
                }
            }
        })
    )
}
editmodify=(e)=>{    //代运营查看详情
    let sid = e.target.parentNode.parentNode.firstChild.nextSibling.innerText
    let id = e.target.parentNode.parentNode.firstChild.nextSibling.nextSibling.innerText
    tools.loginView(this).then(
        $.ajax({
            type:'post',
            url:tools.apiUrl+'operation/settlement_info',
            data:{
                token:localStorage.token,
                id,
            },
            success:(res)=>{
                if(res.status ==1){
                    this.setState({
                        editmodifyvisible:true,
                        operationdata:res.result,
                        operationSid:id
                    })
                }else{
                    message.error(res.msg)
                }
            }
        })
    )
}

pagechange=(pagination, filters, sorter)=>{        //改变页码回调
    tools.loginView(this).then(
        $.ajax({
            type:'post',
            url: tools.apiUrl+this.props.location.state.url+'?page='+pagination.current,
            data:{
                token:localStorage.token
            },
            success:(res)=>{
                let service = res.result.bank_service
                let data = res.result.data
                if(res.status ==1){
                    let cTabContent = this.props.location.state.id ==29?this.tabDataFrom(data):(this.props.location.state.id ==31?this.replaceDataForm(data,service):false);
                    this.setState({
                        // marketdata:res.result.data,
                        cTabContent
                    })
                }else{
                    message.error(res.msg)
                }
            }
        })
    )
}

handleSearchCb=(data)=>{        //搜索
    data.token = localStorage.token;
    if(data.time && data.time.length > 0) {
        if(this.props.location.state.id ==31){
            data.start_time = new Date(data.time[0]._d.getTime()).toLocaleDateString();
            data.end_time = new Date(data.time[1]._d.getTime()).toLocaleDateString();
            data.time = '';
        }
    }
    tools.loginView(this).then(
        $.ajax({
            url: tools.apiUrl+this.props.location.state.url,  //?page=1
            type :'Post',
            data:data,
            success:(res)=>{
            let service = res.result.bank_service
            let data = res.result.data
            if(res.status ==1){
                let cTabContent = this.props.location.state.id ==29?this.tabDataFrom(data):(this.props.location.state.id ==31?this.replaceDataForm(data,service):false);
                this.setState({
                    marketpage:res.result.page,
                    cTabContent,
                })
            }else{
                message.error(res.msg)
            }
            }
        })
    )
}

addOperationModal=(num)=>{     //点击添加--弹出添加对话框
    if(num ==2){
        tools.loginView(this).then(
            $.ajax({
                type:'post',
                url:tools.apiUrl+"operation/shop_info",
                data:{
                    token:localStorage.token,
                    id:this.state.Selectedata[0].id
                },success:(res)=>{
                    this.setState({
                        Editshopdetials:res.result
                    })
                }
            })
        )
    }
    this.setState({
        addReplacevisible:true,
        numtype:num
    })
}
startend=(data)=>{   //开始结束暂停回调
    // console.log(data)
}
addReplaceCancel=()=>{
    this.setState({
        addReplacevisible:false
    })
}
Modifylistcontent=()=>{             //添加后刷新页面
    $.ajax({
        url: tools.apiUrl+this.props.location.state.url,  //?page=1
        type :'Post',
        data:{
            token:localStorage.token
        },
        success:(res)=>{
          let service = res.result.bank_service
          let data = res.result.data
          if(res.status ==1){
            let cTabContent = this.props.location.state.id ==29?this.tabDataFrom(data):(this.props.location.state.id ==31?this.replaceDataForm(data,service):false);
              this.setState({
                  marketpage:res.result.page,
                  cTabContent,
              })
          }else{
            message.error(res.msg)
          }
        }
      })
}

operationcancel=(obj)=>{       //取消详情
    if(obj ==2){
        this.agentlist();
    }
    this.setState({
        editmodifyvisible:false
    })
}
Accountcancel=()=>{
    this.setState({
        Accountvisible:false
    })
}

detailCancel=()=>{
    this.setState({
        detailvisible:false
    })
}

accmanage=()=>{                //代运营账号管理
    this.setState({
        Accountvisible:true
    })
}

rowSelection = {   //列表和选择回调
    onChange: (selectedRowKeys, selectedRows) => {
      if(selectedRowKeys.length == 1){
        this.setState({
          newbutton:{
            border:'1px solid #4A90E2',
            borderRadius: '100px',
            width:'88px',
            height:'30px',
            color:'#4A90E2',
            marginLeft:'30px'
          },
          disabled:false,
          Selectedata:selectedRows
        })
      }else{
        this.setState({
          newbutton:{
            background: '#D8D8D8',
            borderRadius: '100px',
            width:'88px',
            height:'30px',
            color:'#999999',
            marginLeft:'30px',
          },
          disabled:'disabled'
        })
      }
    },
    type: 'radio',
}

// DetailsSettlement=()=>{             //结算--代运营
//     if(this.state.Selectedata){
//         if(this.state.Selectedata[0].status ==2){
//             tools.loginView(this).then(
//                 $.ajax({
//                     type:'post',
//                     url:tools.apiUrl+"operation/settlement_handle",
//                     data:{
//                     token:localStorage.token,
//                     id:this.state.Selectedata[0].id
//                     },
//                     success:(res)=>{
//                     if(res.status ==1){
//                         this.agentlist();
//                     }else{
//                         message.error(res.msg)
//                     }
//                     }
//                 })
//             )
//         }else{
//             message.error('只能是运行中的能结算！')
//         }
//     }
    
// }

// paymoney=()=>{              //打款---代运营
//     if(this.state.Selectedata){
//         if(this.state.Selectedata[0].status ==5 && this.state.Selectedata[0].is_pay ==1){
//             tools.loginView(this).then(
//                 $.ajax({
//                     type:'post',
//                     url:tools.apiUrl+'operation/pay_handle',
//                     data:{
//                     token:localStorage.token,
//                     id:this.state.Selectedata[0].id
//                     },
//                     success:(res)=>{
//                     if(res.status==1){
//                         this.agentlist();
//                     }else{
//                         message.error(res.msg)
//                     }
//                     }
//                 })
//             )
//         }else{
//             message.error("运营状态需为已结束或需未打款")
//         }
//     }
// }


render() {
    const newbutton={
        border:'1px solid #4A90E2',
        borderRadius: '34px',
        width:'88px',
        height:'30px',
        color:'#4A90E2',
        marginLeft:'30px'
    }
    return (
        <div>
            <div className="search-top">
                <SearchPanel 
                    onSearchCb={this.handleSearchCb}
                    searchKeys={this.props.location.state.id ==29?this.state.searchtype1:(this.props.location.state.id ==31?this.state.searchtype2:false)}
                />
            </div>
            <div className="search-content">
                <div className="city-biaotou">
                    {this.props.location.state.id == 29 ? <div className="city-biaotou-left">       {/*营销活动*/}
                        <Button key="btn2" datastyle={newbutton} onClick={this.addMarketModal} >添加账号</Button> 
                        <Button key="btn3" datastyle={this.state.newbutton} disabled={this.state.disabled} onClick={()=>this.startend(1)}>暂停</Button> 
                        <Button key="btn4" datastyle={this.state.newbutton} disabled={this.state.disabled} onClick={()=>this.startend(2)}>开始</Button>
                        <Button key="btn5" datastyle={this.state.newbutton} disabled={this.state.disabled} onClick={()=>this.startend(3)}>结束</Button>
                        <Button key="btn6" datastyle={this.state.newbutton} disabled={this.state.disabled} onClick={this.addshowModal} >修改</Button>
                    </div>:
                    <div className="city-biaotou-left">  {/*代运营*/}
                        <Button key="btn1" datastyle={newbutton} onClick={()=>this.addOperationModal(1)} >添加</Button> 
                        <Button key="btn2" datastyle={this.state.newbutton} disabled={this.state.disabled} onClick={()=>this.addOperationModal(2)}>编辑</Button> 
                        {/* <Button key="btn3" datastyle={this.state.newbutton} disabled={this.state.disabled} onClick={this.DetailsSettlement}>结算</Button>
                        <Button key="btn4" datastyle={this.state.newbutton} disabled={this.state.disabled} onClick={this.paymoney}>打款</Button> */}
                        <Button key="btn5" datastyle={newbutton}   onClick={this.accmanage}>账号管理</Button>
                       
                    </div>}
                   
                </div>
                <div className="search-result-box">
                    <Table 
                        rowSelection={this.rowSelection}
                        columns={this.columns}
                        dataSource={this.state.cTabContent}
                        onChange={this.pagechange}
                        scroll={{ x: 1700 }}
                        pagination={{showQuickJumper:true,total:this.state.marketpage?this.state.marketpage.last_page*10:false}}
                    />
                </div>
            </div>
            <ViewDetail show={this.state.detailvisible} onCancel={this.detailCancel}  viewdata={this.state.viewdata}></ViewDetail>   {/*营销活动详情*/}
            <AddReplaceShop show={this.state.addReplacevisible}  onCancel={this.addReplaceCancel} Modifylistcontent={this.Modifylistcontent} Editshopdetials={this.state.Editshopdetials}
                Selectedata={this.state.Selectedata} type={this.state.numtype}></AddReplaceShop> {/*代运营添加*/}
            <OperationDetails show={this.state.editmodifyvisible} onCancel={this.operationcancel} operationdata={this.state.operationdata?this.state.operationdata:false} operationSid={this.state.operationSid?this.state.operationSid:false}></OperationDetails>
            <OperationAccount show={this.state.Accountvisible} onCancel={this.Accountcancel}></OperationAccount>
        </div>
    )
}
}
export default MarketingActivities